﻿using System;
using System.IO;
using System.Xml.Serialization;
using NLog;

namespace Cubicle.Core.Config
{
    [Serializable]
    [XmlRoot(ElementName = "config")]
    public class BaseConfig
    {
        private static Logger _nlog = LogManager.GetCurrentClassLogger();
        private const string ConfigFileName = "conf.xml";

        public static T Read<T>(string fileName = ConfigFileName)
        {
            var path = String.Empty;
            try
            {
                path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigFileName);
                if (!File.Exists(path)) path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin", ConfigFileName);
                if (!File.Exists(path)) throw new Exception("File not found.");
                using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    var xmls = new XmlSerializer(typeof(T));
                    var result = (T)xmls.Deserialize((fs));
                    _nlog.Info(() => String.Format("Loaded config file: {0}", path));
                    return result;
                }
            }
            catch (Exception ex)
            {
                _nlog.ErrorException("Error reading config file. FileName = " + path, ex);
                throw;
            }
        }
    }
}